<template>
  <span>
    <el-button
      type="success"
      plain
      class="el-icon-upload2"
      size="mini"
      @click="export_excel_visibel = true"
    >
      {{ label }}
    </el-button>
    <el-dialog
      :visible.sync="export_excel_visibel"
      :append-to-body="true"
      width="400px"
    >
      {{ confirm_text }}

      <el-dialog
        width="400px"
        title="选择下载的列"
        :visible.sync="inner_visible"
        :append-to-body="true"
        center
      >
        <!-- <elCheckDiv></elCheckDiv> -->
        <el-select v-model="upload_column" multiple placeholder="请选择">
          <el-option
            v-for="item in tableInfo"
            :key="item.prop"
            :label="item.label"
            :value="item.label"
          ></el-option>
        </el-select>
        <div slot="footer" class="dialog-footer">
          <el-button @click="inner_visible = false">取 消</el-button>
          <el-button type="primary" @click="exportExcel">确 定</el-button>
        </div>
      </el-dialog>

      <div slot="footer" class="dialog-footer">
        <el-button @click="export_excel_visibel = false">取 消</el-button>
        <el-button type="primary" @click="inner_visible = true">
          确 定
        </el-button>
      </div>
    </el-dialog>
  </span>
</template>

<script>
import FileSaver from 'file-saver'
import XLSX from 'xlsx'
import elCheckDiv from '@/components/ElCheckDiv'
export default {
  components: {
    elCheckDiv,
  },
  props: {
    id: {
      type: String, //table ID名称
      default: '',
    },
    label: {
      type: String,
      default: '导出表格',
    },
    multipleSelection: {
      type: Array, // 选中的信息
      default: [],
    },
    tableData: {
      type: Array, // 所有信息
      default: [],
    },
    tableInfo: {
      type: Object, // 表单信息
    },
  },
  data() {
    return {
      export_excel_visibel: false, // 下载弹窗可见
      inner_visible: false, // 内弹窗可见
      confirm_text: '', // 弹窗提示
      upload_column: [], //选择下载的列
      upload_row: [], // 选中的行
    }
  },
  watch: {
    inner_visible: {
      handler(val) {
        if (!val) this.upload_column = []
      },
    },
    multipleSelection: {
      handler(val) {
        if (val.length === 0) {
          this.confirm_text = '确认导出所有行？'
          this.upload_row = this.tableData
        } else {
          this.confirm_text = '确认导出选中行？'
          this.upload_row = val
        }
      },
      immediate: true,
      deep: true,
    },
  },
  methods: {
    //定义导出Excel表格事件
    exportExcel() {
      let _this = this
      let blob = _this.transTableDataToBlob(this.upload_row)
      _this.openDownloadDialog(
        blob,
        '导出 ' + this.$moment(new Date()).format('YYYY/MM/DD') + '.xlsx',
      )
      this.export_excel_visibel = false
      this.inner_visible = false
    },
    // 将表格内容转化为Excel blob
    transTableDataToBlob(selectTableData) {
      let aoa = [[...this.upload_column]]
      for (let i in selectTableData) {
        let row = selectTableData[i]
        let column = []
        let keys = Object.keys(row)
        for (let k in this.tableInfo) {
          let item = this.tableInfo[k]
          if (keys.includes(k) && this.upload_column.includes(item.label)) {
            column.push(row[k])
          }
        }
        aoa.push(column)
      }
      let sheet = XLSX.utils.aoa_to_sheet(aoa)
      let sheetName = 'sheet1'
      let workbook = {
        SheetNames: [sheetName],
        Sheets: {},
      }
      workbook.Sheets[sheetName] = sheet
      let xlsx = XLSX.write(workbook, {
        bookType: 'xlsx', // 生成的文件格式
        bookSST: true, // 是否生成Shared String Table，官方解释是，如果开启生成速度会下降，但在低版本IOS设备上有更好的兼容性
        type: 'array', // 编码方式
      })
      let blob = new Blob([xlsx], { type: 'application/octet-stream' })
      return blob
    },
    // 打开下载框
    openDownloadDialog(url, saveName) {
      if (typeof url == 'object' && url instanceof Blob) {
        url = URL.createObjectURL(url) // 创建blob地址
      }
      let aLink = document.createElement('a')
      aLink.href = url
      aLink.download = saveName || '' // HTML5新增的属性，指定保存文件名，可以不要后缀，注意，file:///模式下不会生效
      let event
      if (window.MouseEvent) event = new MouseEvent('click')
      else {
        event = document.createEvent('MouseEvents')
        event.initMouseEvent(
          'click',
          true,
          false,
          window,
          0,
          0,
          0,
          0,
          0,
          false,
          false,
          false,
          false,
          0,
          null,
        )
      }
      aLink.dispatchEvent(event)
    },
  },
}
</script>
